<template>
  <div class="table">
    <div class="container">
      <el-container>
        <el-header>
          <div class="goods-category-btns">
            <div>
              <el-button type="primary" @click="addGoodsCate">
                <i class="el-icon-plus"></i> 新增分类
              </el-button>
              <category_import ref="categoryImport" style="display: inline;margin-left: 80px" />
              <!-- <el-button type="default" @click="delAllGoodsCate"><i class="el-icon-delete"></i> 删除分类</el-button> -->
            </div>
            <div>
              <el-button type="primary" @click="toCSale">一键同步商城</el-button>
              <el-button type="primary" @click="fetchCategoryList">刷新</el-button>
              <el-button type="default" @click="backToGoodsList">
                <i class="el-icon-back"></i> 返回
              </el-button>
            </div>
          </div>
        </el-header>
        <el-main v-loading="goodsCateLoading">
          <tree-table
            :columns="columns"
            :data="data"
            :expand-all="true"
            ref="categoryTable"
            :selectionFn="onSelectionChange"
          >
            <el-table-column label="排序值" prop="sort">
              <!--<template slot-scope="scope">-->
              <!--<el-input-number class="category-sort" v-model="scope.row.sort"-->
              <!--controls-position="right" :min="0">-->
              <!--</el-input-number>-->
              <!--</template>-->
            </el-table-column>
            <el-table-column label="批量上下架" show-overflow-tooltip>
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.categoryType"
                  :active-value="1"
                  :inactive-value="0"
                  @change="changeShow(scope.row.categoryType , scope.row.id)"
                ></el-switch>
              </template>
            </el-table-column>
            <el-table-column label="分类图标">
              <template slot-scope="scope">
                <img :src="scope.row.logo" class="category-logo" />
                <!-- <el-upload
                                    class="category-logo-uploader"
                                    action="https://jsonplaceholder.typicode.com/posts/"
                                    :show-file-list="false">
                                    <i v-else class="el-icon-plus category-uploader-icon"></i>
                </el-upload>-->
              </template>
            </el-table-column>
            <el-table-column label="新增子分类">
              <template slot-scope="scope">
                <el-button
                  v-if="scope.row._level == 1"
                  type="primary"
                  @click="addSubGoodsCate(scope.row)"
                  size="small"
                >新增</el-button>
              </template>
            </el-table-column>
            <!--<el-table-column label="商品批量操作" width="150px">-->
            <!--<template slot-scope="scope">-->
            <!--<el-button type="primary" round @click="changeMarketable(true,scope.row.id)" size="small">上架</el-button>-->
            <!--<el-button type="primary" round @click="changeMarketable(false,scope.row.id)" size="small">下架</el-button>-->
            <!--</template>-->
            <!--</el-table-column>-->
            <el-table-column label="分类操作" width="150px">
              <template slot-scope="scope">
                <el-button type="primary" @click="editGoodsCate(scope.row)" size="small">编辑</el-button>
                <el-button type="danger" @click="delGoodsCate(scope.row)" size="small">删除</el-button>
              </template>
            </el-table-column>
          </tree-table>
        </el-main>
      </el-container>
    </div>
  </div>
</template>

<script>
import Request from "./../request.js";
import { toSalecCategory } from "../../../api/salec/storecategory";
import {
  changeCategoryStatus,
  offGoodsByCate
} from "../../../api/scm/goods/goods";
import category_import from "@/components/goods/excel_import/goods_category_import";

export default {
  data() {
    return {
      request: new Request(),
      // 字典
      columns: [
        {
          text: "分类名称",
          value: "name"
        },
        {
          text: "分类ID",
          value: "id"
        }
        // {
        //     text: '排序',
        //     value: 'sort',
        //     width: 100
        // },
        // {
        //     text: '分类图标',
        //     value: 'logo'
        // },
        // {
        //     text: '父级ID',
        //     value: 'parentId'
        // }
      ],
      // goodsCategories: dictionary.goodsCategories,
      // 状态
      goodsCateLoading: true,
      delTipsVisible: false,
      // 分类数据
      data: [],
      selectionData: [],
      fly: 1
    };
  },
  mounted() {
    this.fetchCategoryList();
  },
  components: {
    category_import
  },
  methods: {
    fetchCategoryList() {
      this.request.fetchCategoryList({}).then(res => {
        if (res.code == "200") {
          let data = this.$utils.listToTree(res.ext);
          data.forEach(function(item) {
            item.categoryType = parseInt(item.categoryType);
            if (item.goodsStatus == 0 && item.isMaletable == 1) {
              item.flag = true;
            }
            if (item.goodsStatus == 1 && item.isMaletable == 0) {
              item.flag = false;
            }
            item.children.forEach(child => {
              child.categoryType = parseInt(child.categoryType);
              if (child.goodsStatus == 0 && child.isMaletable == 1) {
                child.flag = true;
              }
              if (child.goodsStatus == 1 && child.isMaletable == 0) {
                child.flag = false;
              }
            });
          });
          this.data = data;
          this.goodsCateLoading = false;
          this.$message.success("刷新成功");
        } else if (res.code == "983") {
          this.data = [];
          this.goodsCateLoading = false;
        } else {
          this.$message.error("请求失败");
        }
      });
    },
    // //上下架
    // modifyGoodsStatus(value, id) {
    //   return offGoodsByCate({
    //     id: id,
    //     flag: value
    //   })
    // },
    // changeMarketable(value, id) {
    //   let tips = value ? '上架' : '下架'
    //   this.modifyGoodsStatus(value,id).then(res => {
    //     if (res.data.code == 0) {
    //       this.$message.success(tips + '成功')
    //     } else {
    //       this.$message.error(tips + '失败')
    //     }
    //     this.loading = true
    //     this.fetchCategoryList()
    //   })
    // },
    //是否显示
    changeShow(value, id) {
      if (this.fly != 1) {
        this.$message.error("请勿重复点击");
        return false;
      }
      this.fly = 0;
      changeCategoryStatus({
        id: id,
        categoryType: value
      }).then(res => {
        if (res.data.code == 0) {
          this.$message.success("设置成功");
          var _this = this;
          setTimeout(function() {
            _this.fly = 1;
          }, 1000);
        } else {
          this.$message.error("设置失败");
          var _this = this;
          setTimeout(function() {
            _this.fly = 1;
          }, 1000);
        }
      });
      let flag = true;
      if (value == 1) {
        flag = true;
      } else {
        flag = false;
      }
      offGoodsByCate({ id: id, flag: flag }).then(res => {
        if (res.data.code == 0) {
          var _this = this;
          setTimeout(function() {
            _this.fly = 1;
          }, 1000);
        } else {
          var _this = this;
          setTimeout(function() {
            _this.fly = 1;
          }, 1000);
        }
        this.loading = true;
        this.fetchCategoryList();
      });
    },
    //////////////
    addGoodsCate(row) {
      this.$router.push({
        path: "/goods/addGoodsCate"
      });
    },
    addSubGoodsCate(row) {
      this.$router.push({
        path: "/goods/addGoodsCate",
        query: {
          parentId: row.id,
          parentName: row.name
        }
      });
    },
    editGoodsCate(row) {
      let parentId = row.parentId,
        parentName = "";

      parentName = this.getCategoryName(this.data, parentId);
      this.$router.push({
        path: "/goods/editGoodsCate",
        query: {
          categoryId: row.id,
          categoryName: row.name,
          parentId: row.parentId,
          parentName: parentName,
          sort: row.sort,
          logo: row.logo,
          categoryType: row.categoryType
        }
      });
    },
    delGoodsCate(row) {
      // console.log(row);
      let categoryIds = [];
      categoryIds.push(row.id);
      // this.delTipsVisible = false
      this.$confirm("确认删除？")
        .then(_ => {
          this.request
            .deleteGoodsCategory({
              categoryIds
            })
            .then(res => {
              if (res.code == 200) {
                this.$message.success("删除分类成功");
                this.fetchCategoryList();
              } else {
                this.$message.error("删除分类失败");
              }
            });
        })
        .catch(_ => {});
    },
    delAllGoodsCate() {
      let categories = this.$refs.categoryTable;
      console.log(categories);
    },
    backToGoodsList() {
      console.log("object");
      this.$router.push("/goods/goodsList");
    },
    onSelectionChange(selection) {
      let table = this.$refs.categoryTable;
      console.log(selection);

      // todo 当选中父级分类时, 同时选中子分类
      // toggleRowSelection
      this.selectionData = selection;
    },
    getCategoryName(data, id) {
      let categoryName = "";
      data.map(item => {
        if (item.id == id) {
          categoryName = item.name;
        } else if (item.children && item.children.length > 0) {
          this.getCategoryName(item.children, id);
        }
      });
      return categoryName;
    },
    toCSale() {
      toSalecCategory().then(res => {
        if ((res.code = 200)) {
          this.$message.success("同步成功");
        } else {
          this.$message.error("同步失败");
        }
      });
    }
  }
};
</script>

<style scoped>
.category-sort {
  width: 100px;
}
.category-logo {
  width: 60px;
  height: 60px;
  border-radius: 6px;
}
.category-uploader-icon {
  line-height: 60px;
}
.goods-category-btns {
  display: flex;
  justify-content: space-between;
  padding: 20px 0;
}
.el-main {
  height: calc(100vh - 200px);
  overflow: auto;
}
.el-table__header-wrapper {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
}
</style>



